var app = getApp();
var db = wx.cloud.database();
var userCollection = db.collection("usersDataList");
var recordCollection = db.collection("recordsData");
import { formatData, handleTags } from "../../utils/formatData";
import { expleData } from "../../utils/mean";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    xy: "<",
    flag: null,
    isHaveData: false,
    goinsertText: "建档",
    myBirthDate: "",
    navBarTxt: "",
    active: 0,
    activeBtn: 1,
    hospitalBtn: 1,
    projectBtn: 1,
    reduce: false,
    changeCardItem: false,
    searchShow: false,
    isSearch: false,
    hospitalRadio: "所有",
    projectRadio: "所有",
    savedData: null,
    expleData: expleData,
    twoChangeData: [],
    selfDataList: [],
    indexMyselfData: true,
    tipsRed: [
      "低头读写",
      "歪头读写",
      "握笔过低",
      "眼或鼻过敏",
      "日近用眼2~3小时除学校",
    ],
    tipsGreen: ["未戴镜", "调节力训练", "眼部理疗", "中草药", "日户外0~1小时"],
    projectTag: [
      "所有",
      "眼轴",
      "小瞳",
      "散瞳",
      "裸视",
      "眼压",
      "前房",
      "晶厚",
    ],
    hospitalTag: ["所有", "爱尔眼科", "希玛眼科"],
    noteShow: false,
    currentNote: null,
    shortNavBarTxt: "",
    originalData: [], // 用于存储原始数据
    currentViewState: {
      // 用于存储当前视图状态
      reduce: false,
      changeCardItem: false,
      isSearch: false,
      activeBtn: 1,
      hospitalBtn: 1,
      projectBtn: 1,
    },
    isShared: false,
  },
  // 更新视图状态
  updateViewState(newState) {
    this.setData({
      currentViewState: {
        ...this.data.currentViewState,
        ...newState,
      },
    });
  },
  // 应用视图状态到数据
  applyViewStateToData(data) {
    return data.map((item) => ({
      ...item,
      reduce: this.data.currentViewState.reduce,
      changeCardItem: this.data.currentViewState.changeCardItem,
      isSearch: this.data.currentViewState.isSearch,
    }));
  },
  onConfirm() {
    try {
      // 如果是首次点击确认，保存原始数据
      if (!this.data.originalData || this.data.originalData.length === 0) {
        this.setData({
          originalData: [...this.data.twoChangeData],
        });
      }
      if (this.data.hospitalBtn !== 1 || this.data.projectBtn !== 1) {
        // 获取选中的医院名称
        const selectedHospital =
          this.data.hospitalTag[this.data.hospitalBtn - 1];
        // 使用原始数据进行筛选
        const sourceData = this.data.originalData;
        const filteredData = sourceData.filter((item) => {
          return item.selfMag && item.selfMag.hospital === selectedHospital;
        });

        this.setData(
          {
            isSearch: true,
            twoChangeData: filteredData,
          },
          () => {
            // 筛选后调用 changBtn 方法，传入当前视图类型
            this.changBtn({
              currentTarget: {
                dataset: {
                  item: this.data.activeBtn,
                },
              },
            });
          }
        );
      } else {
        this.setData(
          {
            isSearch: false,
            twoChangeData: this.data.originalData,
          },
          () => {
            // 恢复原始数据后调用 changBtn 方法，传入当前视图类型
            this.changBtn({
              currentTarget: {
                dataset: {
                  item: this.data.activeBtn,
                },
              },
            });
          }
        );
      }
    } catch (error) {
      console.error("筛选数据时出错：", error);
      wx.showToast({
        title: "操作失败，请重试",
        icon: "none",
      });
    } finally {
      this.setData({
        searchShow: false,
      });
    }
  },
  onCancel() {
    this.setData({
      searchShow: false,
    });
  },
  toggleCardItem(e) {
    this.setData({
      [`twoChangeData[${e.currentTarget.dataset.index}].changeCardItem`]:
        !e.currentTarget.dataset.flag,
    });
  },
  changRadio(e) {
    const currentIndex = e.currentTarget.dataset.index;
    const currentFlag = e.currentTarget.dataset.flag;

    // 如果是取消选择
    if (currentFlag) {
      // 如果有保存的数据，则恢复到保存的状态
      if (this.data.savedData) {
        this.setData({
          twoChangeData: this.data.savedData,
          savedData: null, // 清除保存的数据
        });
      } else {
        // 如果没有保存的数据，则恢复原始数据
        const restoredData = this.data.originalData.map((item) => ({
          ...item,
          isRadio: true,
          changRadio: false,
          isCompare: false,
        }));

        this.setData({
          twoChangeData: restoredData,
        });
      }
      return;
    }

    // 如果是首次选择，保存当前数据状态
    if (!this.data.savedData) {
      this.setData({
        savedData: JSON.parse(JSON.stringify(this.data.twoChangeData)), // 深拷贝当前数据
      });
    }

    // 如果是选择
    const selectedCount = this.data.twoChangeData.filter(
      (item) => item.changRadio
    ).length;

    // 如果这是第二条数据的选择
    if (selectedCount === 1) {
      // 获取选中的两条数据
      const selectedData = this.data.twoChangeData.filter(
        (item) =>
          item.changRadio || item === this.data.twoChangeData[currentIndex]
      );

      // 使用 handleTags 处理选中的两条数据
      const processedData = handleTags([...selectedData]).map((item) => ({
        ...item,
        isRadio: true,
        isCompare: true,
        changRadio: true,
        reduce: this.data.reduce,
        changeCardItem: this.data.changeCardItem,
      }));

      this.setData({
        twoChangeData: processedData,
      });
      return;
    }

    // 正常的选择操作
    this.setData({
      [`twoChangeData[${currentIndex}].changRadio`]: true,
      [`twoChangeData[${currentIndex}].isRadio`]: true,
    });
  },
  changeSearchBtn(e) {
    try {
      const item = e.currentTarget.dataset.item;

      if (item == 1) {
        // 切换 reduce 状态
        const newReduce = !this.data.currentViewState.reduce;
        this.updateViewState({ reduce: newReduce });
        this.setData({
          twoChangeData: this.data.twoChangeData.map((item) => ({
            ...item,
            reduce: newReduce,
          })),
          reduce: newReduce,
        });
      } else if (item == 2) {
        // 切换 changeCardItem 状态
        const newChangeCardItem = !this.data.currentViewState.changeCardItem;
        this.updateViewState({ changeCardItem: newChangeCardItem });
        this.setData({
          twoChangeData: this.data.twoChangeData.map((item) => ({
            ...item,
            changeCardItem: newChangeCardItem,
          })),
          changeCardItem: newChangeCardItem,
        });
      } else if (item == 3) {
        this.setData({
          searchShow: true,
        });
      } else if (item == 4) {
        const newCompare = !this.data.twoChangeData[0].compare;
        this.setData({
          twoChangeData: this.data.twoChangeData.map((item) => ({
            ...item,
            compare: newCompare,
          })),
        });
      }
    } catch (error) {
      console.error("切换搜索按钮状态时出错：", error);
      wx.showToast({
        title: "操作失败，请重试",
        icon: "none",
      });
    }
  },
  toggleSearchShow() {
    this.setData({
      searchShow: !this.data.searchShow,
    });
  },
  onChange() {
    wx.navigateTo({
      url: "/pages/homeEchart/homeEchart",
    });
  },
  changBtn(e) {
    try {
      let value = e.currentTarget.dataset.item;

      // 更新视图状态
      this.updateViewState({ activeBtn: value });

      // 根据不同的视图类型处理数据
      let processedData;
      if (value == 1) {
        // 列表视图 - 展示所有数据，取消勾选状态，保留筛选条件
        let sourceData = this.data.originalData;
        if (this.data.hospitalBtn !== 1 || this.data.projectBtn !== 1) {
          const selectedHospital =
            this.data.hospitalTag[this.data.hospitalBtn - 1];
          sourceData = sourceData.filter(
            (item) => item.selfMag && item.selfMag.hospital === selectedHospital
          );
        }
        processedData = sourceData.map((item) => ({
          ...item,
          isRadio: false,
          changRadio: false,
          isCompare: false,
          reduce: this.data.reduce,
          changeCardItem: this.data.changeCardItem,
        }));
      } else if (value == 2) {
        // 时间线视图 - 展示所有数据，取消勾选状态，保留筛选条件
        let sourceData = this.data.originalData;
        if (this.data.hospitalBtn !== 1 || this.data.projectBtn !== 1) {
          const selectedHospital =
            this.data.hospitalTag[this.data.hospitalBtn - 1];
          sourceData = sourceData.filter(
            (item) => item.selfMag && item.selfMag.hospital === selectedHospital
          );
        }
        processedData = handleTags([...sourceData]).map((item) => ({
          ...item,
          isRadio: false,
          isCompare: true,
          changRadio: false,
          reduce: this.data.reduce,
          changeCardItem: this.data.changeCardItem,
        }));
      } else {
        // 选择对比视图 - 保持当前筛选状态
        processedData = this.data.twoChangeData.map((item) => ({
          ...item,
          isRadio: true,
          isCompare: false,
          changRadio: false,
          reduce: this.data.reduce,
          changeCardItem: this.data.changeCardItem,
        }));
      }

      // 应用当前视图状态
      processedData = this.applyViewStateToData(processedData);

      this.setData({
        twoChangeData: processedData,
        activeBtn: value,
      });
    } catch (error) {
      console.error("切换视图时出错：", error);
      wx.showToast({
        title: "操作失败，请重试",
        icon: "none",
      });
    }
  },
  changeTag(e) {
    this.setData({
      hospitalBtn: e.currentTarget.dataset.item,
    });
  },
  changeproTag(e) {
    this.setData({
      projectBtn: e.currentTarget.dataset.item,
    });
  },
  showExpleData() {
    wx.setStorageSync("homeFlag", 1);
    this.setData({
      navBarTxt: `退轴了小程序`,
      twoChangeData: this.data.expleData,
      originalData: this.data.expleData,
      isHaveData: true,
      flag: 1,
    });
  },
  gotoInsetDataPage() {
    if (this.data.goinsertText == "建档") {
      wx.navigateTo({
        url: "/pages/updateMsg/updateMsg",
      });
    } else {
      wx.navigateTo({
        url: "/pages/checklist/checklist",
      });
    }
  },
  // 更新导航栏文本
  updateNavBarText() {
    let newText = "退轴了小程序"; // 默认文本
    const openid = wx.getStorageSync("openid"); // 获取当前用户的 openid
    const sharedOpenid = wx.getStorageSync("sharedOpenid"); // 获取分享者的openid
    const sharedUserId = wx.getStorageSync("sharedUserId"); // 获取分享者的userId

    // 如果是分享进入，使用分享者的数据
    if (this.data.isShared && sharedOpenid && sharedUserId) {
      console.log(this.data.isShared);
      console.log(sharedOpenid);
      console.log(sharedUserId);

      recordCollection
        .where({
          _openid: sharedOpenid,
          _id: Number(sharedUserId),
        })
        .get({
          success: (res) => {
            if (res.data && res.data.length > 0) {
              const recordsData = res.data[0].recordsdata;
              const sharedUserdata = res.data[0].userdata;
              this.setData({
                sharedUserdata: sharedUserdata,
              });
              if (recordsData) {
                try {
                  const { sortedData, hospitalTag } = formatData(
                    recordsData,
                    sharedUserdata
                  );
                  this.setData({
                    hospitalTag: hospitalTag,
                    twoChangeData: [...sortedData],
                    originalData: [...sortedData],
                    activeBtn: 1,
                    isHaveData: true,
                    navBarTxt: `${sharedUserdata.nickName} · 退轴了小程序`,
                  });
                } catch (error) {
                  console.error("处理分享数据时出错：", error);
                }
              }
            }
          },
          fail: (err) => {
            wx.showToast({
              title: "获取分享数据失败",
              icon: "none",
            });
          },
        });
      return;
    } else {
      wx.setStorageSync("isShared", false);
      this.setData({
        isShared: false,
      });
    }

    // 根据 flag 参数决定数据加载方式
    if (this.data.flag == 1) {
      this.setData({
        navBarTxt: `退轴了小程序`,
        twoChangeData: this.data.expleData,
        originalData: this.data.expleData,
        isHaveData: true,
      });
      return;
    }

    // 原有的数据加载逻辑
    userCollection
      .where({
        _openid: openid,
      })
      .get({
        success: (res) => {
          if (res.data.length == 0) {
            this.setData({
              navBarTxt: newText,
              isHaveData: false,
              twoChangeData: [],
              goinsertText: "建档",
            });
            console.log(this.data.navBarTxt);

            return;
          }

          let nickName = "";
          const selectedUserId = wx.getStorageSync("selectedUserId");

          // 如果建档后的用户没有检查单，则显示建档
          if (res.data[0].records && res.data[0].records.length > 0) {
            if (selectedUserId) {
              // 根据 selectedUserId 查找匹配的记录
              const matchedRecord = res.data[0].records.find(
                (record) => record.id === selectedUserId
              );
              if (matchedRecord) {
                nickName = matchedRecord.nickName;
                // 更新数据
                this.setData({
                  userData: res.data,
                  isHaveData: true,
                  goinsertText: "录入检查单",
                  myBirthDate: matchedRecord.birthDate,
                });
              }
            } else {
              // 如果没有 selectedUserId，使用最后一条记录
              const lastIndex = res.data[0].records.length - 1;
              nickName = res.data[0].records[lastIndex].nickName;
              // 设置最后一条记录的birthDate
              this.setData({
                myBirthDate: res.data[0].records[lastIndex].birthDate,
                isHaveData: true,
                goinsertText: "录入检查单",
              });
            }
          }

          if (nickName) {
            this.setData({
              navBarTxt: `${nickName} · 退轴了小程序`,
            });
          }

          // 确保上面的判断都完成后再执行下面的查询
          if (selectedUserId) {
            recordCollection
              .where({
                _openid: openid,
                _id: selectedUserId,
              })
              .get({
                success: (res) => {
                  console.log("获取自己的数据成功：", res);
                  if (res.data && res.data.length > 0) {
                    const recordsData = res.data[0].recordsdata;
                    const sharedUserdata = res.data[0].userdata;

                    if (recordsData) {
                      try {
                        const { sortedData, hospitalTag } = formatData(
                          recordsData,
                          sharedUserdata
                        );
                        // console.log(sortedData, "home");

                        // return;
                        this.setData({
                          hospitalTag: hospitalTag,
                        });

                        this.setData({
                          twoChangeData: [...sortedData],
                          originalData: [...sortedData],
                          activeBtn: 1,
                        });
                        console.log(this.data.twoChangeData);
                      } catch (error) {}
                    } else {
                      this.setData({
                        twoChangeData: [],
                        originalData: [], // 同时清空 originalData
                      });
                    }
                  } else {
                    this.setData({
                      twoChangeData: [],
                      originalData: [], // 同时清空 originalData
                    });
                  }
                },
                fail: (err) => {
                  wx.showToast({
                    title: "获取数据失败",
                    icon: "none",
                  });
                },
                complete: () => {
                  wx.hideLoading();
                },
              });
          }
        },
        fail: (err) => {
          this.setData({
            navBarTxt: newText,
            isHaveData: false,
          });
        },
      });
  },

  // 跳转到添加页面
  addPage() {
    wx.navigateTo({
      url: "/pages/addPage/addPage",
    });
  },
  changeUserPage() {
    if (this.data.flag == 1 || this.data.isShared) {
      wx.navigateTo({
        url: "/pages/addPage/addPage",
      });
    } else {
      wx.navigateTo({
        url: "/pages/changeUser/changeUser",
      });
    }
  },
  // 跳转到首页
  goIndexPage() {
    wx.navigateTo({
      url: "/pages/index/index",
    });
  },
  gettimestamp: function (timestamp) {
    if (!timestamp) return "";
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 检查是否是分享进入
    if (
      options.shared === "true" &&
      options.openid &&
      options.userId &&
      options.birthDate
    ) {
      // 保存分享者的openid、userId和birthDate
      wx.setStorageSync("sharedOpenid", options.openid);
      wx.setStorageSync("sharedUserId", options.userId);
      wx.setStorageSync("isShared", true);
      this.setData({
        isShared: true,
        myBirthDate: options.birthDate,
      });
    } else {
      // 非分享进入时，确保isShared为false
      wx.setStorageSync("isShared", false);
      this.setData({
        isShared: false,
      });
    }

    this.updateViewState({
      reduce: this.data.reduce,
      changeCardItem: this.data.changeCardItem,
      isSearch: this.data.isSearch,
      activeBtn: this.data.activeBtn,
      hospitalBtn: this.data.hospitalBtn,
      projectBtn: this.data.projectBtn,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 从本地存储获取参数
    const flag = wx.getStorageSync("homeFlag");
    const isShared = wx.getStorageSync("isShared");

    if (flag) {
      this.setData({
        flag: flag,
      });
    } else {
      this.setData({
        flag: null,
      });
    }

    // 确保isShared状态正确
    this.setData({
      isShared: isShared || false,
    });

    this.updateNavBarText();

    // 重置按钮状态和过滤条件
    this.setData({
      reduce: false,
      changeCardItem: false,
      isSearch: false,
      searchShow: false,
      hospitalBtn: 1, // 重置医院选择为"所有"
      projectBtn: 1, // 重置项目选择为"所有"
      hospitalRadio: "所有", // 重置医院单选值
      projectRadio: "所有", // 重置项目单选值
    });

    // 更新视图状态
    this.updateViewState({
      reduce: false,
      changeCardItem: false,
      isSearch: false,
      hospitalBtn: 1,
      projectBtn: 1,
    });

    // 确保数据状态与视图状态一致
    if (this.data.twoChangeData.length > 0) {
      const processedData = this.applyViewStateToData(this.data.twoChangeData);
      this.setData({
        twoChangeData: processedData,
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const openid = wx.getStorageSync("openid");
    const selectedUserId = wx.getStorageSync("selectedUserId");
    const nickName = this.data.navBarTxt.split("·")[0].trim();
    const myBirthDate = this.data.myBirthDate;

    return {
      title: `${nickName}的近视检查数据`,
      desc: "查看我的近视检查数据",
      path: `/pages/home/home?shared=true&openid=${openid}&userId=${selectedUserId}&birthDate=${myBirthDate}`,
      imageUrl: "../../images/share.png",
      success: function (res) {
        wx.showToast({
          title: "分享成功",
          icon: "success",
        });
      },
      fail: function (res) {
        wx.showToast({
          title: "分享失败",
          icon: "none",
        });
      },
    };
  },
  // 显示防控笔记弹窗
  showNoteDetail(e) {
    const index = e.currentTarget.dataset.index;
    const currentNote = this.data.twoChangeData[index];
    const shortNavBarTxt = this.data.navBarTxt.split("·")[0];
    this.setData({
      noteShow: true,
      currentNote: currentNote,
      shortNavBarTxt: shortNavBarTxt,
    });
  },

  // 关闭防控笔记弹窗
  toggleNoteShow() {
    this.setData({
      noteShow: false,
    });
  },

  // 阻止事件冒泡
  stopPropagation(e) {
    e.stopPropagation();
  },

  // 编辑数据
  editData(e) {
    const index = e.currentTarget.dataset.index;
    const currentData = this.data.twoChangeData[index];

    // 将数据转换为可编辑的格式
    const editData = currentData;

    // 将数据存储到本地，以便在编辑页面使用
    wx.setStorageSync("editData", JSON.stringify(editData));

    // 跳转到编辑页面
    wx.navigateTo({
      url: "/pages/checklist/checklist?mode=edit",
      success: () => {
        console.log("跳转到编辑页面成功");
      },
      fail: (err) => {
        console.error("跳转失败：", err);
        wx.showToast({
          title: "跳转失败",
          icon: "none",
        });
      },
    });
  },
});
